<?php

namespace App\Controller\Admin;

use App\Model\ArtCategoryModel;
use App\Model\ArtModel;
use App\Setting\ArtSetting;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

use Symfony\Component\HttpFoundation\Request;
use App\Base\BaseController4Admin;
use App\Entity\Art as Entity;

/**
 * @route("/admin/")
 */
class ArtController extends BaseController4Admin
{

    /**
     * @route("Art/add",name="ArtPreAdd")
     */
    public function add()
    {
        $request = Request::createFromGlobals();
        $uid = $this->needToBeAdmin();
        if (!$cat = $this->getParamRequired("cat")) {$cat = 0;}
        //通用代码
        $this->setSetting(new ArtSetting($this->getDoctrine()));
        $entity = "";
        if (!$entity) {$entity = new $this->entitySetting->entityPath();}
        $setting = new ArtSetting($this->getDoctrine());
        $from = $this->getFormCreator()->createAddFrom($entity,$setting->formConfig($cat),$this->generateUrl("ArtDoAdd"));

        $refer = $request->headers->all()["referer"][0];
        $data = array(
            "title" => $this->entitySetting->entityCnName,
            "show"   => $from->createView(),
            "isAdd"   => true,
            "cat"   => $cat,
            "refer"   => "",
        );
        return $this->render("Admin/Art/edit.php.twig",$data);
    }

    /**
     * @route("Art/add/do",name="ArtDoAdd")
     *
     *
     */
    public function doAdd(Request $request)
    {
        $uid = $this->needToBeAdmin();
        if (!$cat = $this->getParamRequired("cat")) {$cat = 0;}
        $entity = new Entity();
        if (!$entity) {
            $entity = new $this->entitySetting->entityPath();
        }
        $setting = new ArtSetting($this->getDoctrine());
        if ($entity = $this->getFormCreator()->fillEntity($entity,$request,$setting->formConfig())) {
            /**@var $entity Entity*/
            if ($entity->getAdddate()) {
                $entity->setAddtime(strtotime($entity->getAdddate()));
            }else{
                $entity->setAddtime(time())->setAdddate(date($this->YYMMDDHHIISS));
            }
            $entity->setUpdatetime(time())->setUpdatedate(date($this->YYMMDDHHIISS));
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            $urlData = ["cat"=>$cat];//传参
            return $this->js_out("保存成功",$this->generateUrl("ArtLists",$urlData));
        } else {
            return $this->js_out("系统错误，请联系管理员",$this->generateUrl("ArtPreAdd"));
        }
    }

    /**
     * @route("Art/edit/{id}",name="ArtPreEdit")
     */
    public function edit(Entity $entity)
    {
        $request = Request::createFromGlobals();
        $uid = $this->needToBeAdmin();
        if (!$cat = $this->getParamRequired("cat")) {$cat = 0;}
        $this->setSetting(new ArtSetting($this->getDoctrine()));
        $setting = new ArtSetting($this->getDoctrine());
        $from = $this->getFormCreator()->createAddFrom($entity,$setting->formConfig($cat),$this->generateUrl("ArtDoEdit",["id"=>$entity->getId()]));
        if (!$refer = $this->getParamRequired("refer")) {$refer="";}
        $refer = $request->headers->all()["referer"][0];
        $data = array(
            "title" => $this->entitySetting->entityCnName,
            "show"   => $from->createView(),
            "isAdd"   => false,
            "cat"   => $cat,
            "refer"   => $refer,
        );
        return $this->render("Admin/Art/edit.php.twig",$data);
    }

    /**
     * @route("Art/edit/{id}/do",name="ArtDoEdit")
     *
     *
     */
    public function doEdit(Request $request,Entity $entity)
    {
        $uid = $this->needToBeAdmin();
        $this->setSetting(new ArtSetting($this->getDoctrine()));
        if (!$cat = $this->getParamRequired("cat")) {$cat = 0;}
        $setting = new ArtSetting($this->getDoctrine());
        if ($entity = $this->getFormCreator()->fillEntity($entity,$request,$setting->formConfig())) {
            /**@var $entity Entity*/
            if ($entity->getAdddate()) {
                $entity->setAddtime(strtotime($entity->getAdddate()));
            }else{
                $entity->setAddtime(time())->setAdddate(date($this->YYMMDDHHIISS));
            }
            $entity->setUpdatetime(time())->setUpdatedate(date($this->YYMMDDHHIISS));
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            $urlData = ["cat"=>$cat];
            return $this->js_out("保存成功",$this->generateUrl("ArtLists",$urlData));
        } else {
            return $this->js_out("系统错误，请联系管理员",$this->generateUrl("ArtPreEdit",array("id"=>$entity->getId())));
        }
    }

    /**
     * @route("Art",name="ArtLists")
     */
    public function lists()
    {
        $uid = $this->needToBeAdmin();
        if (!$cat = $this->getParamRequired("cat")) {$cat = 0;}
        //私有部分
        $tools = array();
        $ArtCategoryModel = new ArtCategoryModel($this->getDoctrine());
        $category = $ArtCategoryModel->getAllArtCategoryTree();
        unset($category[0]);
//        var_dump($category);
        $catEntity = false;
        if ($cat) {
            $catEntity = $ArtCategoryModel->getById($cat);
            $newCatSelectData = [];
            foreach ($category as $one) {
                if ($one["link"] == $catEntity->getLink()) {
                    $newCatSelectData[]=$one;
                }
            }
            $category = $newCatSelectData;



        }



//        $tools["category"] = $category;
        $tools["is_Hot"] = [["id"=>"0","name"=>"非热门"],["id"=>"1","name"=>"热门文章"]];
        $tools["is_Top"] = [["id"=>"0","name"=>"非置顶"],["id"=>"1","name"=>"置顶文章"]];
//        $tools["is_Index"] = [["id"=>"0","name"=>"未置顶"],["id"=>"1","name"=>"已置顶"]];

        //通用部分
        $this->setSetting(new ArtSetting($this->getDoctrine()));
        /*分页配置*/
        if (!$page   = $this->getParamRequired("page")) { $page = 1;}
        $per_page   = $this->entitySetting->perPage;
        $model = new ArtModel($this->getDoctrine());
        $params = array();
        $request = Request::createFromGlobals();
        $txtKeywords = $request->get("txtKeywords");
        if ( $condition = $request->get("cond") ) {
            foreach ( $condition as $key => $val ) {
                if ($val === "") {
                    continue;
                }
                $params["conditions"][$this->entitySetting->table][$key]["eq"]=$val;
            }
        }
        if ($catEntity) {
//            var_dump($catEntity);
            $params["conditions"]["ArtCategory"]["link"]["eq"]=$catEntity->getLink();
        }

        if ($txtKeywords) {
            $params["textKey"] = "%$txtKeywords%";
        }
        $table = str_replace("_","",$this->entitySetting->table);
        $params["groupBy"][$table]=array("id");
        $lists = $model->getAdminLists($params,$page * $per_page - $per_page,$per_page);

        //$lists = $this->getLists($page,$per_page);
        $total = $lists["total"];
        $this->smartFormat($lists["data"]);

        /*URL配置*/
        $urls = array(
            "toolUrl"=>$this->generateUrl("ArtTools"),
            "addUrl"=>$this->generateUrl("ArtPreAdd"),
        );
        $entityCnName = $this->entitySetting->entityCnName;
        return $this->render("Admin/Art/list.php.twig", array(
            'title'     => "$entityCnName 列表",
            "tools"     => $tools,
            "cat"       => $cat,
            'urls'      => $urls,
            'lists'     => $lists["data"],
            'page'      => $this->creatPage($this->generateUrl("ArtLists"),$total,$per_page),
        ));
    }

    /**
     * @route("Art/tools",name="ArtTools")
     */
    public function tools(Request $request)
    {
        $uid = $this->needToBeAdmin();
        $this->setSetting(new ArtSetting($this->getDoctrine()));
//        return $this->comTools($request);
        if($__EVENTTARGET = $this->getParamRequired("__EVENTTARGET")){
            unset($_GET['__EVENTTARGET']);
        }else{
            return $this->js_out("参数丢失",$this->redirectToRoute($this->entitySetting->entityName."Lists"));
        }
        if($__EVENTARGUMENT = $this->getParamRequired("__EVENTARGUMENT")){
            unset($_GET['__EVENTARGUMENT']);
        }
        $em = $this->getDoctrine()->getManager();
        //如果是删除操作执行删除操作
        if ($__EVENTTARGET == "multiDelete") {
            if($ids = $this->getParamRequired("ids")){
                unset($_GET['ids']);
            }else{
                return $this->js_out("参数丢失",$this->redirectToRoute($this->entitySetting->entityName."Lists"));
            }
            if (is_array($ids) && !empty($ids)) {
                foreach ($ids as $id) {
                    if (property_exists($this->entitySetting,"noDelete")) {

                        if (in_array(0,$this->entitySetting->noDelete)) {
                            continue;
                        }
                        if (in_array($id,$this->entitySetting->noDelete)) {
                            continue;
                        }
                    }
                    $entity  = $em->find($this->entitySetting->bundleName.":".$this->entitySetting->entityName,$id);
                    $em->remove($entity);
                }
                $em->flush();
            }
        }
        //如果是修改操作执行修改操作
        if ($__EVENTTARGET == "setAttr") {
            parse_str($__EVENTARGUMENT,$data);
            if (is_array($data) && isset($data["id"])) {
                $entity  = $em->find($this->entitySetting->bundleName.":".$this->entitySetting->entityName,$data["id"]);
                unset($data["id"]);
                foreach ($data as $key => $val) {
                    if ( !in_array( $key , $this->entitySetting->editKeys ) ) { continue; }
                    $func = "set$key";
                    $func = str_replace("_","",$func);
                    $entity->$func($val);
                }
                $em->persist($entity);
                $em->flush();
            }
        }
        //否则将参数传递至list
        $cond["cond"] = $request->get("cond");
        $queryStr = http_build_query($cond);
        if ($txtKeywords = $request->get("txtKeywords")) {
            $queryStr .= "&txtKeywords=".$txtKeywords;
        }
        if ($cat = $this->getParamRequired("cat")) {
            $queryStr .= "&cat=".$cat;
        }
        return $this->redirect($this->generateUrl($this->entitySetting->entityName."Lists")."?".$queryStr);
    }

    /**
     * @route("Art/copy/{id}",name="ArtDoCopy")
     *
     * @Method({"GET", "POST"})
     */
    public function doCopy(Request $request,Entity $entity)
    {
        $tmp = $entity;
        $tmp = $this->toArray($tmp);
        $en = new Entity();
        foreach ($tmp as $key => $value) {
            if ($key == "id") {continue;}
            $funcGet = "get".ucfirst($key);
            $funcSet = "set".ucfirst($key);
            $en->$funcSet($entity->$funcGet());
        }
        /**@var $en Entity*/
        //需要更新的内容是创建时间和更新时间
        $en->setAddtime(time())
            ->setAdddate(date($this->YYMMDDHHIISS))
            ->setUpdatetime(time())
            ->setUpdatedate(date($this->YYMMDDHHIISS));

        $this->myEm()->persist($en);$this->myEm()->flush();
        return $this->redirectToRoute("ArtLists");
    }

}
